package com.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

/*
说明
1. SimpleChannelInboundHandler 是 ChannelInboundHandlerAdapter
2. HttpObject 客户端和服务器端相互通讯的数据被封装成 HttpObject
 */
public class MyHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    //channelRead0 读取客户端数据
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject msg) throws Exception {
        //判断 msg 是不是 httprequest请求
        if (msg instanceof HttpRequest){
            //获取URI,进行过滤
            HttpRequest request = (HttpRequest) msg;
            //System.out.println(request.uri());
            URI uri = new URI(request.uri());
            //System.out.println(uri.getPath());
            if (uri.getPath().equals("/favicon.ico")){
                System.out.println("请求了 favicon.ico, 不做响应");
                return;
            }
            //查看请求的通道信息
            System.out.println("客户端请求的通道的hashcode: > "+channelHandlerContext.channel().hashCode());
            //查看请求的地址信息
            System.out.println("请求的地址信息: < "+ channelHandlerContext.channel().remoteAddress());
            //查看请求的通道
            System.out.println("请求管道信息: --->"+channelHandlerContext.pipeline().hashCode());
            //查看一下msg的类型
            System.out.println("msg类型: "+msg.getClass());
            //查看客户端的地址
            System.out.println("客户端的地址是"+channelHandlerContext.channel().remoteAddress());
            //回复信息给浏览器 [http协议]
            ByteBuf content = Unpooled.copiedBuffer("hello 浏览器客户端!", CharsetUtil.UTF_8);
            //构造一个http的响应，即 httpresponse
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,content);
            //配置响应头的信息
            response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());//响应内容的长度
            //将构建好 response返回
            channelHandlerContext.writeAndFlush(response);

        }
    }
}
